'use strict';

angular
	.module('sinnerG')
	.constant('dados', [
		{
			name:'Hugo',
			phone:'6342768374',
			photo:null,
			email: 'ksd@djsa.com'
		},
		{
			name:'Bruno',
			phone:'1231231',
			photo:null,
			email: 'sdfsd@ss.com'
		},
		{
			name:'Ricardo',
			phone:'7565443',
			photo:null,
			email: 'sedfsd@ss.pt'
		}
	]
	)
	.controller('AppCtrl', ['$rootScope','$http','$log' ,function ($rootScope, $http, $log) {
		$rootScope.model={
			user:{},
			searchresults:[]
		};
		$rootScope.model.authenticate=function(){
			$http({
				method:'post',
				url:'http://10.250.22.173:8080/sinnerg/api/login',
				data:{
					username:$rootScope.model.username,
					password:$rootScope.model.password
				}
			}).then(
				function(response){
					$log.log('response', response);
					if(response && response.status===200){
						$rootScope.model.user={
							username:$rootScope.model.username
						};
					}else{
						$rootScope.model.errorlogin=true;
					}
				},
				function(error){
					$log.error('response', error);
					$rootScope.model.errorlogin=true;
				}
			);
		};
		//$rootScope.model.user.username='UserTest';
	}])
	  
	.controller('MainCtrl', ['$rootScope','$scope','$http','dados', function ($rootScope,$scope,$http, dados) {
		$scope.model.logout=function(){
			$http({
				method:'post',
				url:'http://10.250.22.173:8080/sinnerg/api/logout'
			}).then(
				function(){
					$rootScope.model={user:{}};
				},
				function(){
					$rootScope.model={user:{}};
				}
			);
		};
	  
		$scope.model.search=function(query){
				/*var nomes=[];
				angular.forEach(dados,function(dado){
					nomes.push(dado.name);
				});
				return nomes; */
			if(!query){
				return [];
			}
			$scope.model.show=false;
			$http({
				method:'get',
				url:'http://10.250.22.173:8080/sinnerg/api/search',
				params:{query:query}
			}).then(
				function(results){
					/*results.data=dados;*/
					$scope.model.searchresults=results.data;
					var names=[];
					angular.forEach(results.data || [],function(user){
						names.push(user.name);
					});
					return names;
				},
				function(){
					return [];
				}
			);
		};
		
		$scope.model.showresults=function(){
			$scope.model.show=true;
		};
	   
	}
]);
